package com.aaa.dao;

import com.aaa.entity.Ptype;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 商品管理dao实现类
 */
@Repository
public class PtypeDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private RowMapper<Ptype> rowMapper=new RowMapper<Ptype>() {
        public Ptype mapRow(ResultSet resultSet, int i) throws SQLException {
            Ptype ptype = new Ptype();
            ptype.setTid(resultSet.getLong("tid"));
            ptype.setTname(resultSet.getString("tname"));
            return ptype;
        }
    };
    public List<Ptype> ptypeList(String keyword, Integer offset, Integer limit) {
        String sql="select tid,tname from ptype where tname like ? order by tid desc limit ?,?";
        List<Ptype> query = this.jdbcTemplate.query(sql, rowMapper, "%" + keyword + "%", offset, limit);
        return query;
    }

    public Integer count(String keyword) {
        String sql="select count(tid) as c from ptype";
        List<Integer> count = this.jdbcTemplate.query(sql, new RowMapper<Integer>() {
            public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getInt("c");
            }
        });
        Integer integer = Integer.valueOf(count.get(0).toString());
        return integer;
    }

    public Integer save(Ptype ptype) {
        String sql="insert into ptype(tname) values(?)";
        int update = this.jdbcTemplate.update(sql, ptype.getTname());

        return update;
    }

    public Integer update(Ptype ptype) {
        String sql="update ptype set tname=? where tid=?";
        int update = this.jdbcTemplate.update(sql, ptype.getTname(),ptype.getTid());
        return update;
    }

    public Integer delete(Integer tid) {
        String sql="delete from ptype where tid=?";
        int update = this.jdbcTemplate.update(sql, tid);
        return update;
    }
}
